# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import sys
import threading

try:
    from SimpleHTTPServer import SimpleHTTPRequestHandler
except ImportError:
    from http.server import SimpleHTTPRequestHandler

try:
    from BaseHTTPServer import HTTPServer
except ImportError:
    from http.server import HTTPServer

ROOT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
# PUBLIC_RESOURCE_PREFIX = '/static'
PUBLIC_DIRECTORY = os.path.join(ROOT_DIRECTORY, 'content')
os.chdir(PUBLIC_DIRECTORY)

class MyRequestHandler(SimpleHTTPRequestHandler, object):
    '''
    def translate_path(self, path):
        if self.path.startswith(PUBLIC_RESOURCE_PREFIX):
            if self.path == PUBLIC_RESOURCE_PREFIX or self.path == PUBLIC_RESOURCE_PREFIX + '/':
                return PUBLIC_DIRECTORY + '/index.html'
            else:
                return PUBLIC_DIRECTORY + path[len(PUBLIC_RESOURCE_PREFIX):]
        else:
            return super(MyRequestHandler, self).translate_path(path)
    '''
    pass


def run_server():
    try:
        server_address = ('0.0.0.0', 8998)
        httpd = HTTPServer(server_address, MyRequestHandler)
        print('visit by [http://{host}:{port}]'.format(
            host=server_address[0],
            port=server_address[1]
        ))
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('closing...')
    finally:
        httpd.server_close()

try:
    thread = threading.Thread(None, run_server)
    thread.daemon=True
    thread.start()
    while thread.isAlive(): 
        thread.join(1)
    # ... do things ...

    # Shutdown server
    # server.shutdown()
except (KeyboardInterrupt, SystemExit):
    print('closing ...')
    import time
    time.sleep(3) # seconds
    print('exit')
    sys.exit(0)
